﻿using System;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;


namespace sqlserverextensions.Helper
{
    internal static class ExceptionHelper
    {
        internal static void EvaluateException(Exception ex, Int16 errSeverity = 16)
        {
            // Connect to server in event of error
            using (SqlConnection conn = new SqlConnection("context connection=true"))
            {
                conn.Open();

                // Generate error response to SQL Server
                string msg = string.Format("RAISERROR('{0}', {1}, 1)", ex.Message.Replace('\'', ' '), errSeverity);
                using (SqlCommand cmd = new SqlCommand(msg, conn))
                {

                    try
                    {
                        // Execute error on SQL Server
                        SqlPipe sqlpipe = SqlContext.Pipe;
                        sqlpipe.ExecuteAndSend(cmd);
                        Exception newEx = new Exception(msg);
                        throw newEx;
                    }
                    catch {  } // Prevent error duplication
                }
            }        
        
        }
    }
}
